package com.zxkj.ssm.weixin.shop.utils;
import static org.apache.commons.logging.LogFactory.getLog;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.springframework.ui.ModelMap;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 *@Author 程序媛
 *@Date 2018/6/30 10:31
 *@Description  Fremarker 模板操作基类
 *@Version
 */
public class FreeMarkerUtils {
    private final static Log log = getLog(FreeMarkerUtils.class);

    /**
     * @param templateFilePath 模板文件路径
     * @param destFilePath 生成的目标路径
     * @param config 配置
     * @param model 数据模型
     * @throws IOException
     * @throws TemplateException
     */
    public static void makeFileByFile(String templateFilePath, String destFilePath, Configuration config,
            Map<String, Object> model) throws IOException, TemplateException {
        makeFileByFile(templateFilePath, destFilePath, config, model, true, false);
    }

    /**
     * @param templateFilePath 模板文件路径
     * @param destFilePath  生成的目标路径
     * @param config 
     * @param model 数据模型
     * @param override
     * @throws IOException
     * @throws TemplateException
     */
    public static void makeFileByFile(String templateFilePath, String destFilePath, Configuration config,
            Map<String, Object> model, boolean override) throws IOException, TemplateException {
        makeFileByFile(templateFilePath, destFilePath, config, model, override, false);
    }

    /**
     * @param templateFilePath  模板文件路径
     * @param destFilePath 生成的目标路径
     * @param config
     * @param model 数据模型
     * @param override
     * @param append   true，则将字节写入文件末尾处，而不是写入文件开始处
     * @throws IOException
     * @throws TemplateException
     */
    public static void makeFileByFile(String templateFilePath, String destFilePath, Configuration config,
            Map<String, Object> model, boolean override, boolean append) throws IOException, TemplateException {
        Template t = config.getTemplate(templateFilePath);
        File destFile = new File(destFilePath);
        if (override || append || !destFile.exists()) {
            File parent = destFile.getParentFile();
            if (null != parent) {
                parent.mkdirs();
            }
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile, append), "utf-8"));
            t.process(model, out);
            out.close();
            log.info(destFilePath + "    saved！");
        } else {
            log.error(destFilePath + "    already exists！");
        }
    }

        /**
         *
         * @param classpath 类路径下加载模板
         * @return
         */
       public static Configuration  getConfiguration(String classpath){
                    Configuration configuration =new Configuration(Configuration.VERSION_2_3_26);
                    configuration.setClassForTemplateLoading(FreeMarkerUtils.class,classpath);
                 return configuration;
     }


    /***
     * @param templateFilePath 模板文件
     * @param destFilePath 目标目录文件位置
     * @param config 配置
     * @param model 数据模型
     * @return int整形
     * @throws IOException
     * @throws TemplateException throws IOException, TemplateException
     */
    public static int  staticCreateHtml(String templateFilePath, String destFilePath, Configuration config,
            Map<String, Object> model)throws IOException, TemplateException{
	    		Template template=null;
	    		FileOutputStream fos = null;
	    		Writer out = null;
	    		try {
					 template=	config.getTemplate(templateFilePath);
					 File file = new File(destFilePath);
				     file.getParentFile().mkdirs();
				         fos = new FileOutputStream(file);
				         out = new OutputStreamWriter(fos, "UTF-8");
				         template.process(model, new BufferedWriter(out));
				       }catch (FileNotFoundException e) {
				         return -3;
				       }catch (UnsupportedEncodingException e){
				         return -4;
				       }catch (TemplateException e){
				         return -1;
				       }catch (IOException e){
				         return -2;
				       }catch(Exception e){
				    	   e.printStackTrace();
				    	   return -1;
				       } finally {
				    	   if (out != null) {
					             out.flush();
					             out.close();
					           }
					           if (fos != null)
					             fos.close();
				         }  
	    				return 1;
    }
    /**
     * @param template 模板文件
     * @param configuration
     * @return
     */
    public static String makeStringByFile(String template, Configuration configuration) {
        return makeStringByFile(template, configuration, new ModelMap());
    }

    /**
     * @param template 模板文件
     * @param configuration 
     * @param model 数据模型
     * @return
     */
    public static String makeStringByFile(String template, Configuration configuration, ModelMap model) {
        try {
            Template tpl = configuration.getTemplate(template);
            return FreeMarkerTemplateUtils.processTemplateIntoString(tpl, model);
        } catch (Exception e) {
            log.error(e.getMessage());
            return "";
        }
    }
    
    /**
     * @param TplFile
     * @param cfg
     * @param modelMap
     */
    public static void  makeStringPrintlnConsole(String TplFile,Configuration cfg,ModelMap modelMap){
			try {
				Template tpl = cfg.getTemplate(TplFile);
				tpl.process(modelMap, new PrintWriter(System.out));
				} catch (IOException e) {
					e.printStackTrace();
				} catch (TemplateException e) {
					e.printStackTrace();
				}
    }
    
    /**
     * @param TplFile
     * @param diseFile
     * @param cfg
     * @param modelMap
     */
    public static void  makeStringPrintlnFile(String TplFile,String diseFile,Configuration cfg,ModelMap modelMap){
    	try {
			Template tpl = cfg.getTemplate(TplFile);
			tpl.process(modelMap, new FileWriter(diseFile));
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TemplateException e) {
				e.printStackTrace();
			}
    }

}
